package fhq.hcmute.edu.vn.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import fhq.hcmute.edu.vn.adapter.ImageAdapter;
import fhq.hcmute.edu.vn.adapter.MyBitmap;
import fhq.hcmute.edu.vn.message.MessageFactory;
import fhq.hcmute.edu.vn.message.MyMessage;
import fhq.hcmute.edu.vn.network.Network;
import fhq.hcmute.edu.vn.network.SendAndReceive;
import fhq.hcmute.edu.vn.util.HandlerRequestUtil;

public class ScannerActivity extends Activity {
	private static final int REQUEST_CODE = 1;
	private ImageView imageView;
	private Button btnRotateLeft;
	private Button btnRotateRight;
	private TextView txtNotification;
	private boolean isShowing = false;
	private boolean isFromGallery = false;
	private ImageAdapter imageAdapter;
	public static Bitmap currentBitmap;
	private View currentSelectedFrame;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scanner);
		init();
	}

	private void init() {
		imageView = (ImageView) findViewById(R.id.imgPicture);
		btnRotateLeft = (Button) findViewById(R.id.btnRotateLeft);
		btnRotateRight = (Button) findViewById(R.id.btnRotateRight);
		txtNotification = (TextView) findViewById(R.id.txtNotification);
		imageAdapter = new ImageAdapter(ScannerActivity.this, imageView);
		imageAdapter.setHandler(handler);
		txtNotification.setOnClickListener(onClickImage);
		imageView.setOnClickListener(onClickImage);
		btnRotateLeft.setOnClickListener(onClickRotateLeft);
		btnRotateRight.setOnClickListener(onClickbRotateRight);
	}

	private void showConfirmDialog(String title, String yesButton,
			String noButton, DialogInterface.OnClickListener positiveButton,
			DialogInterface.OnClickListener negativeButton) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton(yesButton,
						positiveButton)
				.setNegativeButton(noButton,
						negativeButton);
		AlertDialog alert = builder.create();
		alert.show();
	}

	private DialogInterface.OnClickListener onTakeNewPicture =
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					isFromGallery = false;
					startActivityForResult(intent, REQUEST_CODE);
				}
			};
	private DialogInterface.OnClickListener onRemoveAllPictures =
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					imageAdapter.removeAll();
				}
			};
	private DialogInterface.OnClickListener onRemovePicture =
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					imageAdapter.remove(currentSelectedFrame.getId());
				}
			};
	private View.OnClickListener onClickRotateLeft =
			new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					if (isShowing) {
						excuteCommand(MessageFactory
								.createRotateImageLeftMessage());
					}
				}
			};
	private View.OnClickListener onClickbRotateRight =
			new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					if (isShowing) {
						excuteCommand(MessageFactory
								.createRotateImageRightMessage());
					}
				}
			};
	private View.OnClickListener onClickImage = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isShowing) {
				String title = getResources().getString(
						R.string.AlertDialog_Scanner_Message);
				String stringPositive = getResources().getString(
						R.string.AlertDialog_Scanner_Yes);
				String stringNegative = getResources().getString(
						R.string.AlertDialog_Scanner_No);
				showConfirmDialog(title, stringPositive, stringNegative,
						onTakeNewPicture, null);
			} else {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				isFromGallery = false;
				startActivityForResult(intent, REQUEST_CODE);
			}
		}
	};

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == HandlerRequestUtil.TAKE_PICTURE_REQUEST) {
				MyMessage message = (MyMessage) msg.obj;
				if (message != null) {
					if (message.getType() == MessageFactory.RETURN) {
						if (message.getFrom() == MessageFactory.POST_IMAGE) {
							if ((Boolean) message.getFirstData()) {
								Toast.makeText(getApplicationContext(), "ok",
										Toast.LENGTH_SHORT).show();
							}
						} else if (message.getFrom() == MessageFactory.ROTATE_LEFT) {
							if ((Boolean) message.getFirstData()) {
								Matrix matrix = new Matrix();
								matrix.postRotate(-90);
								currentBitmap =
										Bitmap.createBitmap(currentBitmap, 0,
												0,
												currentBitmap.getWidth(),
												currentBitmap.getHeight(),
												matrix,
												true);
								imageView.setImageBitmap(currentBitmap);
							}
						} else if (message.getFrom() == MessageFactory.ROTATE_RIGHT) {
							if ((Boolean) message.getFirstData()) {
								Matrix matrix = new Matrix();
								matrix.postRotate(90);
								currentBitmap =
										Bitmap.createBitmap(currentBitmap, 0,
												0,
												currentBitmap.getWidth(),
												currentBitmap.getHeight(),
												matrix,
												true);
								imageView.setImageBitmap(currentBitmap);
							}
						}
					}
				} else {
					Toast.makeText(getApplicationContext(), "Server is down",
							Toast.LENGTH_SHORT).show();
					finish();
				}
			}
			super.handleMessage(msg);
		}

	};

	private void excuteCommand(MyMessage message) {
		SendAndReceive fromServerTask =
				new SendAndReceive(ScannerActivity.this,
						HandlerRequestUtil.TAKE_PICTURE_REQUEST, handler);
		fromServerTask.execute(message);
	}

	private String saveFile(byte[] byteArray) {
		String sdCard = Environment.getExternalStorageDirectory().getPath();
		File file = new File(sdCard + "/Trackpad Emulator/img_"
				+ SystemClock.elapsedRealtime() + ".jpg");
		File folder = new File(sdCard + "/Trackpad Emulator");
		if (!folder.exists()) {
			folder.mkdirs();
		}
		try {
			FileOutputStream outputStream = new FileOutputStream(file);
			outputStream.write(byteArray);
			outputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return file.getAbsolutePath();
	}

	@Override
	protected void
			onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
			try {
				txtNotification.setVisibility(View.GONE);
				InputStream stream =
						getContentResolver().openInputStream(data.getData());
				byte[] bitmapByteArray = IOUtils.toByteArray(stream);
				stream.close();
				String path = saveFile(bitmapByteArray);
				MyBitmap myBitmap = new MyBitmap(false, path);
				imageAdapter.add(myBitmap);
				isShowing = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (!isFromGallery) {
					getContentResolver().delete(data.getData(), null, null);
				}
			}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.option_menu_scanner_activity, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = new Intent();
		switch (item.getItemId()) {
		case R.id.menuItemPickFromGallery:
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			isFromGallery = true;
			startActivityForResult(intent, REQUEST_CODE);
			break;
		case R.id.menuItemShowTouchPad: {
			intent =
					new Intent(getApplicationContext(), TouchPadActivity.class);
			startActivity(intent);
			break;
		}
		case R.id.menuItemCloseFrame: {
			try {
				Network.getInstance().sendToServer(
						MessageFactory.createCloseFramwMessage());
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		currentSelectedFrame = v;
		getMenuInflater()
				.inflate(R.menu.context_menu_scanner_activity, menu);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int id = currentSelectedFrame.getId();
		String stringPositive = getResources().getString(
				R.string.AlertDialog_Scanner_Yes);
		String stringNegative = getResources().getString(
				R.string.AlertDialog_Scanner_No);
		String title = null;
		switch (item.getItemId()) {
		case R.id.menuItemShow:
			imageAdapter.show(id);
			break;
		case R.id.menuItemRemove:
			title = getResources().getString(
					R.string.AlertDialog_Scanner_Remove_Message);
			showConfirmDialog(title, stringPositive, stringNegative,
					onRemovePicture, null);
			break;
		case R.id.menuItemRemoveAll:
			title = getResources().getString(
					R.string.AlertDialog_Scanner_Remove_All_Message);
			showConfirmDialog(title, stringPositive, stringNegative,
					onRemoveAllPictures, null);
			break;
		}
		return super.onContextItemSelected(item);
	}

	private int count = 0;
	private long lastUpdate;

	@Override
	public void onBackPressed() {
		count++;
		if (count == 1) {
			lastUpdate = System.currentTimeMillis();
			Toast.makeText(getApplicationContext(),
					getString(R.string.press_back), Toast.LENGTH_SHORT)
					.show();
		} else if (count == 2) {
			long actualTime = System.currentTimeMillis();
			if (actualTime - lastUpdate < 3000) {
				super.onBackPressed();
			}
			count = 0;
		}
	}
}
